import os
import time
from datetime import datetime
from django.shortcuts import render, redirect, reverse
from django.http import HttpResponse, JsonResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required, permission_required
from datetime import datetime
from .models import Student
from CRM.settings import MEDIA_ROOT
from .forms import RegisterForms
# Create your views here.

def index(request):

    '''
    l = [1, 2, 3, 4]
    d = {'name': 'lisan', 'age': 20, 'sex': '男'}
    num = 12
    def fun():
        return True
    html = '<h2 style="color:red;">我是安全的，请展示。</h2>'
    goods = [
        {'name': '排骨', 'price': 28.36, 'quantity': 0.446},
        {'name': '油粘米', 'price': 19.52, 'quantity': 3.83},
        {'name': '花生', 'price': 12.98, 'quantity': 0.55},
        {'name': '绿豆', 'price': 14.63, 'quantity': 0.53},
        {'name': '黑米', 'price': 15.65, 'quantity': 0.46},
        {'name': '虫草花', 'price': 4.90, 'quantity': 1},
        {'name': '土豆', 'price': 4.81, 'quantity': 0.19},
        {'name': '西南花', 'price': 21.40, 'quantity': 1},
    ]
    '''
    stus = [
        {'name': '张三', 'age': 10086, 'sex': 0, 'course': ['计算机', '机电', '挖掘机']},
        {'name': '李四', 'age': 12306, 'sex': 1, 'course': ['计算机', '挖掘机']},
        {'name': '王五', 'age': 8080, 'sex': 1, 'course': ['焊工', '挖掘机']},
        {'name': '赵六', 'age': 3306, 'sex': 0, 'course': ['计算机', '厨师', '挖掘机']},
        {'name': '钱七', 'age': 9527, 'sex': 1, 'course': ['机电', '挖掘机']},
        {'name': '孙八', 'age': 6379, 'sex': 1, 'course': ['厨师']},
    ]
    '''
    stus = Student.objects.all()
    n = request.COOKIES.get('n')
    n = int(n) + 1 if n else 1
    response = render(request, 'index.html', context={
        't': datetime.now(),
        'l': l,
        'd': d,
        'fun': fun(),
        'num': num,
        'html': html,
        'goods': goods,
        'stus': stus,
        'tt': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'tformat': '%Y/%m/%d %H:%M:%S',
        'n': n,
    })
    response.set_cookie('n', n)
    return response
    '''

    name = request.session.get('user', '游客')
    return render(request, 'new_index.html', context={
        'name': name,
    })

'''
def login(request):

    if request.method == 'GET':
        return render(request, 'login.html')
    elif request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username == 'zhou' and password == 'jian':
            request.session['name'] = username
            request.session.set_expiry(10)
            return redirect(index)
        else:
            return redirect(login)
'''

def login_view(request):

    next_url = request.GET.get('next')

    # user = request.user # 已登录显示登录用户，未登录显示匿名用户。

    # 判断是否登录
    if request.user.is_authenticated: # 已登录返回True，未登录返回Flase。
        if next_url:
            return redirect(next_url)
        return redirect(reverse('index'))
    # return render(request, 'login.html')

    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        # 校验用户名与密码
        auth = authenticate(username=username, password=password)
        if auth:
            login(request, auth) # 登录，将用户信息保存到session
            if next_url:
                return redirect(next_url)
            return redirect(reverse('index'))
    return render(request, 'login.html')

'''
def logout(request):

    request.session.clear()
    return redirect('index')
'''

def logout_view(request):

    logout(request)
    return redirect(reverse('index'))

def register(request):

    if request.method == 'GET':
        form = RegisterForms()
        return render(request, 'register.html', context={'form': form})
    elif request.method == 'POST':
        form = RegisterForms(request.POST) # 实例化对象，接收了提交的数据！
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            password_re = form.cleaned_data.get('password_repeat')
            email = form.cleaned_data.get('email')
            if password == password_re:
                return HttpResponse('注册成功')
        return render(request, 'register.html', context={'form': form})


def detail(request, name):

    return HttpResponse('这是%s的详情页' % name)

@login_required # 默认未登录时跳转到accounts/login
@permission_required('teacher.view_student', raise_exception=True)
def upload(request):

    # if not request.user.is_authenticated:
    #     return redirect(reverse('login') + '?next={}'.format(request.path_info))

    # if not request.user.has_perm('teacher.view_student'):
    #     return HttpResponse('你无权查看内容')

    if request.method == 'GET':
        return render(request, 'upload.html')
    elif request.method == 'POST':
        file_dir = datetime.now().strftime('%Y%m%d')
        media_file_dir = os.path.join(MEDIA_ROOT, file_dir)
        None if os.path.exists(media_file_dir) else os.mkdir(media_file_dir)
        # file = request.FILES.get('file')
        files = request.FILES.getlist('file')
        for file in files:
            with open(os.path.join(media_file_dir, file.name), 'wb') as f:
                for line in file.chunks(): # 当上传的文件过大时，自动分块。
                    f.write(line)
        return HttpResponse('文件上传成功')


def test(request):

    sex = request.GET.get('sex')
    sex = int(sex)
    res = Student.objects.values('name', 'age', 'sex').filter(sex=sex)
    res = list(res)
    data = {'res': res}
    return JsonResponse(data)